package com.ebupt.migu.music.common.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;


/**
 * @program: workorder
 * @description: 安全认证
 * @author: zhanggk
 * @create: 2019-02-24 15:47
 **/
@Component
public class TokenUtils {
 
    /** 签名秘钥 */
    private static String secret;
    /** 该JWT的签发者 */
    private static String issuer;
    /** 该JWT所面向的用户 */
    private static String subject;
    /** 有效时间，过期会报错 (单位毫秒) */
    private static long ttlMillis;

    @Value("${system.token.secret}")
    public void setSecret(String secret) {
        TokenUtils.secret = secret;
    }

    @Value("${system.token.issuer}")
    public void setIssuer(String issuer) {
        TokenUtils.issuer = issuer;
    }

    @Value("${system.token.subject}")
    public void setSubject(String subject) {
        TokenUtils.subject = subject;
    }

    @Value("${system.token.ttl-millis}")
    public void setTtlMillis(long ttlMillis) {
        TokenUtils.ttlMillis = ttlMillis;
    }

    /**
     * 生成token
     * 默认有效期一天
     * @param id 一般传入userName
     * @return token String
     */
    public static String createJwtToken(String id) {
        return createJwtToken(id, issuer, subject, ttlMillis);
    }
 
    /**
     * 生成Token
     *
     * @param id        编号
     * @param issuer    该JWT的签发者，是否使用是可选的
     * @param subject   该JWT所面向的用户，是否使用是可选的；
     * @param ttlMillis 有效时间，过期会报错 (单位毫秒)
     * @return token String
     */
    private static String createJwtToken(String id, String issuer, String subject, long ttlMillis) {
        // 签名算法 ，将对token进行签名
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
 
        // 生成签发时间
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
 
        // 通过秘钥签名JWT
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(secret);
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
 
        // Let's set the JWT Claims
        JwtBuilder builder = Jwts.builder().setId(id)
                .setIssuedAt(now)
                .setSubject(subject)
                .setIssuer(issuer)
                .signWith(signatureAlgorithm, signingKey);
 
        // if it has been specified, let's add the expiration
        if (ttlMillis >= 0) {
            long expMillis = nowMillis + ttlMillis;
            Date exp = new Date(expMillis);
            builder.setExpiration(exp);
        }

        // Builds the JWT and serializes it to a compact, URL-safe string
        return builder.compact();
    }

    /**
     * Sample method to validate and read the JWT
     * @param jwt
     * @return Claims
     */
    public static Claims parseJWT(String jwt) {
        // This line will throw an exception if it is not a signed JWS (as expected)
        return Jwts.parser()
                .setSigningKey(DatatypeConverter.parseBase64Binary(secret))
                .parseClaimsJws(jwt).getBody();
    }
}